package com.blogsystem.controller;
import com.blogsystem.entity.UserStats;
import org.springframework.security.core.Authentication;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.ui.Model;

import com.blogsystem.service.ArticleService;
import com.blogsystem.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blogsystem.entity.User;
import com.blogsystem.entity.Article;
import com.blogsystem.entity.Comment;
import com.blogsystem.service.ClickCountService;
import com.blogsystem.service.CommentService;
import com.blogsystem.service.UserService;
import com.blogsystem.service.impl.ArticleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ClickCountService clickCountService;

    /**
     * 打开个人中心页面
     */

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@GetMapping("/api/users")
public Page<User> listUsers(@RequestParam(defaultValue = "1") int pageNum,
                            @RequestParam(defaultValue = "10") int pageSize,
                            @RequestParam(required = false) String username) {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    if (username != null && !username.isEmpty()) {
        queryWrapper.like("username", username);
    }
    return userService.page(new Page<>(pageNum, pageSize), queryWrapper);
}

    @GetMapping("/center")
    public String userCenter(Authentication authentication, Model model) {
        // 检查认证信息是否有效且用户已登录（排除匿名用户）
        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            // 获取认证主体对象
            Object principal = authentication.getPrincipal();

            // 判断主体是否为UserDetails类型（Spring Security的用户详情接口）
            if (principal instanceof UserDetails) {
                // 从UserDetails中获取用户名
                String username = ((UserDetails) principal).getUsername();
                // 调用UserService根据用户名查询用户实体
                User user = userService.findByUsername(username);
                
                // 如果查询到用户数据不为空
                if (user != null) {
                    // 获取用户ID用于后续业务操作
                    Integer userId = user.getUserId();
                    // 将用户基本信息添加到Model，供前端页面渲染使用
                    model.addAttribute("user", user);
                    /**
                     * 获取用户统计数据：
                     * 1. 调用 userService.getUserData 方法获取完整的用户数据
                     * 2. 从返回结果中提取键为 "stat" 的统计信息部分
                     * 3. 如果 "stat" 不存在，则使用空Map作为默认值，避免前端访问时出现空指针异常
                     * 4. 将处理后的统计信息添加到 model 中，供前端页面渲染使用
                     */
//                    Map<String, Object> userData = userService.getUserData(authentication);
//                    @SuppressWarnings("unchecked")
//                    Map<String, Object> stat = (Map<String, Object>) userData.get("stat");
//
//                    model.addAttribute("stat", stat != null ? stat : Collections.emptyMap());

                    // 获取用户文章
                    List<Article> articles = articleService.getAllArticlesByUserId(userId);
                    int articleCount = articles.size();

                    // 获取用户评论
                    List<Comment> comments = commentService.getAllCommentsByUserId(userId);
                    int commentCount = comments.size();

                    // 获取用户累计点击量
                    long totalClicks = clickCountService.getUserTotalClicks(userId);


                    // 使用 UserStats 替代 Map
                    UserStats userStats = new UserStats(articleCount, commentCount, totalClicks);

                    model.addAttribute("user", user);
                    model.addAttribute("userStats", userStats); // 添加这个属性



                    System.out.println("文章数量: " + articleCount);

                    System.out.println("评论数量: " + commentCount);
                    System.out.println("点击量: " + totalClicks);


                    // 获取用户草稿和
                    model.addAttribute("draftArticles", userService.getDraftArticles(user.getUserId()));
                    //  待审核文章
                    model.addAttribute("pendingArticles", userService.getPendingArticles(user.getUserId()));

                    //  获取用户的文章和
                    model.addAttribute("myArticles", userService.getArticlesByUserId(user.getUserId()));

                    //  获取用户的评论
                    model.addAttribute("myComments", userService.getCommentsByUserId(user.getUserId()));
                    return "center";
                }
            }
        }
        return "center";
    }

    /**
     * 修改用户密码
     * @param authentication 认证信息
     * @param currentPassword 当前密码
     * @param newPassword 新密码
     * @param confirmPassword 确认新密码
     * @return 响应结果
     */
    @PostMapping("/change-password")
    public String changePassword(Authentication authentication,
                                 @RequestParam String currentPassword,
                                 @RequestParam String newPassword,
                                 @RequestParam String confirmPassword,
                                 Model model) {
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                String username = ((UserDetails) principal).getUsername();
                User user = userService.findByUsername(username);

                // 验证当前用户是否存在
                if (user == null) {
                    model.addAttribute("error", "用户不存在");
                    return "center";
                }

                // 验证当前密码是否正确
                if (!userService.checkPassword(user.getUserId(), currentPassword)) {
                    model.addAttribute("error", "当前密码错误");
                    return "center";
                }

                // 验证两次输入的新密码是否一致
                if (!newPassword.equals(confirmPassword)) {
                    model.addAttribute("error", "两次输入的密码不一致");
                    return "center";
                }

                // 更新密码
                boolean success = userService.updatePassword(user.getUserId(), newPassword);
                if (!success) {
                    model.addAttribute("error", "密码更新失败，请重试");
                    return "center";
                }

                model.addAttribute("success", "密码修改成功");
            }
        } else {
            model.addAttribute("error", "请先登录");
        }
        return "redirect:/user/center"; // 修改成功后跳转到个人中心
    }



    /**
     * 分页查询用户列表（支持用户名/邮箱搜索）
     * @param pageNum 当前页码
     * @param pageSize 每页显示数量
     * @param username 用户名（可选）
     * @param email 邮箱（可选）
     */
    @GetMapping
    public Page<User> listUsers(@RequestParam(defaultValue = "1") int pageNum,
                                @RequestParam(defaultValue = "10") int pageSize,
                                @RequestParam(required = false) String username,
                                @RequestParam(required = false) String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username);
        }
        if (email != null && !email.isEmpty()) {
            queryWrapper.like("email", email);
        }
        return userService.page(new Page<>(pageNum, pageSize), queryWrapper);
    }

    /**
     * 获取当前用户信息
     * @param authentication 认证信息
     * @return 用户信息
     */
    @GetMapping("/current")
    public User getCurrentUser(org.springframework.security.core.Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                String username = ((UserDetails) principal).getUsername();
                return userService.findByUsername(username);
            }
        }
        return null;
    }

    /**
     * 获取用户的文章、评论和统计信息
     * @param authentication 认证信息
     * @return 用户数据
     */
    @GetMapping("/my-data")
    public Map<String, Object> getUserData(org.springframework.security.core.Authentication authentication) {
        Map<String, Object> data = new HashMap<>();

        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                String username = ((UserDetails) principal).getUsername();
                User user = userService.findByUsername(username);

                if (user != null) {
                    Integer userId = user.getUserId();

                    // 获取用户文章
                    List<Article> articles = userService.getArticlesByUserId(userId);
                    int articleCount = articles.size();
                    data.put("articleCount", articleCount);

                    // 获取用户评论
                    List<Comment> comments = userService.getCommentsByUserId(userId);
                    int commentsCount = comments.size();
                    data.put("commentsCount", commentsCount);

                    // 获取用户累计点击量
                    long totalClicks = clickCountService.getUserTotalClicks(userId);
                    data.put("totalClicks", totalClicks);

                }
            }
        }

        return data;
    }

    /**
     * 更新用户头像
     * @param authentication 认证信息
     * @param avatar 新的头像URL
     * @return 更新结果
     */
    @PostMapping("/update-avatar")
    public ResponseEntity<Boolean> updateAvatar(org.springframework.security.core.Authentication authentication, @RequestParam String avatar) {
        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                String username = ((UserDetails) principal).getUsername();
                User user = userService.findByUsername(username);

                if (user != null) {
                    return ResponseEntity.ok(userService.updateAvatar(user.getUserId(), avatar));
                }
            }
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 获取用户的累计点击量
     * @param authentication 认证信息
     * @return 累计点击量
     */
    @GetMapping("/my-clicks")
    public ResponseEntity<Long> getUserClicks(org.springframework.security.core.Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                String username = ((UserDetails) principal).getUsername();
                User user = userService.findByUsername(username);

                if (user != null) {
                    long totalClicks = clickCountService.getUserTotalClicks(user.getUserId());
                    return ResponseEntity.ok(totalClicks);
                }
            }
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 获取当前用户的待审核文章
     */
    @GetMapping("/pending")
    public List<Article> getPendingArticles(org.springframework.security.core.Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
                String username = ((org.springframework.security.core.userdetails.UserDetails) principal).getUsername();
                return articleService.getPendingArticlesByUsername(username);
            }
        }
        return Collections.emptyList();
    }

    /**
     * 获取当前用户的草稿文章
     */
    @GetMapping("/drafts")
    public List<Article> getDraftArticles(org.springframework.security.core.Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
                String username = ((org.springframework.security.core.userdetails.UserDetails) principal).getUsername();
                return articleService.getDraftArticlesByUsername(username);
            }
        }
        return Collections.emptyList();
    }
}